package org.example.flux;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.input.Tailer;
import org.apache.commons.io.input.TailerListener;
import org.apache.commons.io.input.TailerListenerAdapter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Sinks;

import java.io.File;
import java.time.Duration;

/**
 * 页面日志管理器
 *
 * @author 欧阳劲驰
 * @since 0.0.1
 */
@Component
@Slf4j
public class LogManager implements InitializingBean {
    /**
     * 日志插槽
     */
    private final Sinks.Many<String> LOG_SINKS = Sinks.many().replay().all();

    private final static String LOG_DIR = "/Users/aozzl/IDE/IdeaProjects/nio-study/logs/nio-study.log";

    /**
     * 发送日志
     *
     * @param msg 信息
     */
    public void emitLog(String msg) {
            LOG_SINKS.tryEmitNext(msg);
    }

    /**
     * 获取日志流
     *
     * @return 日志流
     */
    public Flux<String> getLog() {
        return LOG_SINKS.asFlux();
    }

    /**
     * 初始化
     */
    @Override
    public void afterPropertiesSet() {
        //模拟日志,这段可以删掉
        new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                log.info("模拟日志");
            }
        }).start();

        // 创建监听器
        TailerListener listener = new TailerListenerAdapter() {
            @Override
            public void handle(String line) {
                emitLog(line);
            }
        };
        // 创建tail线程,并运行
        new Thread(Tailer.builder()
                .setFile(new File(LOG_DIR))
                .setTailerListener(listener)
                .setDelayDuration(Duration.ofMillis(500))
                .setTailFromEnd(false)
                .get()).start();
    }
}
